import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-04-28
 * Time: 20:53
 */
public class HashBucket2<K,V> {
    static class Node<K,V> {
        public K key;
        public V val;

        public Node<K,V> next;

        public Node(K key,V val) {
            this.key = key;
            this.val = val;
        }
    }

    public double loadfactor = 0.75;
    public Node<K,V>[] array = (Node<K,V>[])new Node[10];
    public int usedSize;

    public void put(K key,V val) {
        int index = key.hashCode() % array.length;
        Node<K,V> cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        Node<K,V> newnode = new Node<>(key,val);
        newnode.next = array[index];
        array[index] = newnode;
        this.usedSize++;

        if(loadFactorCount() >= loadfactor) {
            resize();
        }
    }

    private void resize() {
        Node<K,V>[] newArray = (Node<K,V>[]) new Node[2 * array.length];
        for(int i = 0; i < array.length; i++) {
            Node<K,V> cur = array[i];
            while(cur != null) {
                int newIndex = cur.key.hashCode() % newArray.length;
                Node<K,V> curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }

    private double loadFactorCount() {
        return this.usedSize * 1.0 / array.length;
    }

    public V getKey(K key) {
        int index = key.hashCode() % array.length;
        Node<K,V> cur = array[index];
        while(cur != null) {
            if(cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }


}
